package com.aptemo.webetek.client.widgets.games;

import com.aptemo.webetek.client.events.HasPickClickHandlers;
import com.aptemo.webetek.client.events.PickClickEvent;
import com.aptemo.webetek.client.events.PickClickHandler;
import com.aptemo.webetek.shared.EventBean;
import com.aptemo.webetek.shared.PickBean;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;

public class BetPicker
		extends Composite implements HasPickClickHandlers, ClickHandler
{

	private FlexTable	pickPanel	= new FlexTable();
	private EventBean	data;

	public BetPicker()
	{
		initWidget(pickPanel);
	}

	public void setData(EventBean bet)
	{
		this.data = bet;
		// add handlers
		pickPanel.setCellSpacing(2);
		pickPanel.setWidth("100%");

		double val = 100.0 / bet.getPicks().size();
		int i = 0;
		for (PickBean item : bet.getPicks())
		{
			PickRow pick = new PickRow(item);
			pickPanel.getFlexCellFormatter().setWidth(0, i, val + "%");
			pickPanel.setWidget(0, i, pick);
			i++;

			// add handler
			pick.addClickHandler(this);

		}

	}

	@Override
	public HandlerRegistration addPickClickHandler(PickClickHandler handler)
	{
		return addHandler(handler, PickClickEvent.TYPE);
	}

	@Override
	public void onClick(ClickEvent event)
	{
		// get pick
		PickRow pr = (PickRow) event.getSource();
		PickBean pick = pr.getPick();

		fireEvent(new PickClickEvent(pick));

		event.stopPropagation();
	}

	public void selectMine(String pick)
	{
		// find position
		int index = 0;
		for (PickBean dp : data.getPicks())
		{
			if (pick.equals(dp.getId()))
			{
				Widget w = pickPanel.getWidget(0, index);
				// check type
				if (w instanceof PickRow)
				{
					((PickRow) w).setMine();
				}
			}
			index++;
		}
	}

}
